//
//  WRGestureView.m
//  WRGesturePassword
//
//  Created by 王然 on 16/6/24.
//  Copyright © 2016年 wangran. All rights reserved.
//

#import "WRGestureView.h"
#import "WRGestureClickView.h"


#define BaseCircleTag  (600)  //tag的基础值（慎改）
#define CircleAlpha 1.0     //原点透明度
#define LineWidth 0.5       //线条宽度


@interface WRGestureView()

@property (nonatomic , strong) UIColor * normalColor;

@property (nonatomic , strong) UIColor * selectColor;

@property (nonatomic , strong) UIColor * wrongColor;

@property (nonatomic , strong) NSMutableArray * clickVArr;

@property (nonatomic , strong) NSMutableArray * clickVSelectArr;

@property (nonatomic) BOOL isWrong;//是否是错误

@property (nonatomic) BOOL isDrawing;//正在画中

@property (nonatomic , strong) NSTimer * timer;

@property(nonatomic)CGPoint currpoint;

@end

@implementation WRGestureView

- (instancetype)initWithFrame:(CGRect)frame withNormallColor:(UIColor *)normalC withSelectColor:(UIColor *)selectC withWrongColor:(UIColor *)wrongC withIsTraOutPW:(BOOL)isTraOutPW
{
    self = [super initWithFrame:frame];
    if (self) {
        self.normalColor = normalC;
        self.selectColor = selectC;
        self.wrongColor = wrongC;
        self.isTraOutOfPW = isTraOutPW;
        [self setupCircles];
        [self setMultipleTouchEnabled:YES];

        UIPanGestureRecognizer * pangesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pangestureClick:)];
        [self addGestureRecognizer:pangesture];
    }
    return self;
}
- (void)pangestureClick:(UIPanGestureRecognizer *)pangesture
{
    
    CGPoint point = [pangesture locationInView:self];
    switch (pangesture.state) {
        case UIGestureRecognizerStateBegan: {
            self.isDrawing = NO;
            if (self.isWrong) {
                [self clearColorAndSelectClickV];
            }
            [self updateclickVSelectArr:point];
            
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            self.isDrawing = YES;
            self.currpoint = point;
            [self updateclickVSelectArr:point];
            [self setNeedsDisplay];
        }
            break;
        case UIGestureRecognizerStateEnded: {
            self.currpoint = point;
            [self endGestureInput];
            
            break;
        }
        case UIGestureRecognizerStateCancelled:
            [self endGestureInput];
            break;
        default:
        {
            self.currpoint = point;
            [self setNeedsDisplay];
            [self updateclickVSelectArr:point];
        }
            break;
    }
}
- (void)setIsTraOutOfPW:(BOOL)isTraOutOfPW
{
    _isTraOutOfPW = isTraOutOfPW;
    for (WRGestureClickView * clickV in self.clickVArr) {
        clickV.stateType = (self.isTraOutOfPW ? View_Click_Type_Right : View_Click_Type_Normal);
    }
}
- (NSMutableArray *)clickVSelectArr
{
    if (!_clickVSelectArr) {
        _clickVSelectArr = [NSMutableArray array];
    }
    return _clickVSelectArr;
}
- (void)setupCircles
{
    self.clickVArr = [NSMutableArray array];
    
    //初始化9个按钮原点
    NSArray * numArr = @[@1,@2,@3,@4,@5,@6,@7,@8,@9];
    for (int index = 0; index < numArr.count; index ++) {
        
        CGFloat clickVX = CircleBigLeft + (index % 3) * (CircleRadiusDouble + CircleBigMargin);
        CGFloat clickVY = CircleBigLeft + (index / 3) *  (CircleRadiusDouble + CircleBigMargin);
        WRGestureClickView * clickV = [[WRGestureClickView alloc]initWithFrame:CGRectMake( clickVX, clickVY, CircleRadiusDouble, CircleRadiusDouble)];
        [clickV reloadNormallColor:self.normalColor withSelelctColor:self.selectColor withWrongColor:self.wrongColor];
        [clickV setBackgroundColor:[UIColor clearColor]];
        clickV.stateType = (self.isTraOutOfPW ? View_Click_Type_Right : View_Click_Type_Normal);
        clickV.alpha = CircleAlpha;
        clickV.userInteractionEnabled = NO;
        clickV.tag = index + BaseCircleTag + 1; // tag从基数+1开始,
        [self addSubview:clickV];
        [self.clickVArr addObject:clickV];
    }
    self.backgroundColor = [UIColor clearColor];
}
#pragma mark - touch click
//结束绘制手势
- (void)endGestureInput
{
    self.currpoint = [((UIView *)[self.clickVSelectArr lastObject]) center];
    self.isDrawing = NO;
    [self setNeedsDisplay];
    
    NSString * passwordStr = @"";
    //生成密码串
    for (WRGestureClickView * clickV in self.clickVSelectArr) {
        passwordStr = [passwordStr stringByAppendingFormat:@"%zd", (clickV.tag - BaseCircleTag)];
    }
    
    [self clearColorAndSelectClickV];
    
    if ([self.delegate respondsToSelector:@selector(GestureWithPasswordStr:)]) {
        if (passwordStr && passwordStr.length > 0) {
            [self.delegate GestureWithPasswordStr:passwordStr];
        }
    }
    
    
}
//清除绘画的颜色 和选择的按钮
- (void)clearColorAndSelectClickV
{
    if (!self.isDrawing) {
        [self clearColor];
        [self clearSelectectClickV];
    }
}
- (void)clearColor
{
    if (self.isWrong) {
        self.isWrong = NO;
        for (WRGestureClickView * clickV in self.clickVArr) {
            [clickV setStateType:(self.isTraOutOfPW ? View_Click_Type_Right : View_Click_Type_Normal)];
        }
    }
}
- (void)clearSelectectClickV
{
    for (WRGestureClickView * clickV in self.clickVArr) {
        [clickV setSelected:NO];
    }
    [self.clickVSelectArr removeAllObjects];
    [self setNeedsDisplay];
    
}
//根据touches的位置  添加点击的按钮 到 clickVSelectArr 中
- (void)updateclickVSelectArr:(CGPoint)point
{
    for (WRGestureClickView * clickV in self.clickVArr) {
        if (CGRectContainsPoint(clickV.frame, point) && clickV.selected == NO) {
            clickV.selected = YES;
            [self.clickVSelectArr addObject:clickV];
        }
    }
}
//获取当前手指触摸的点
- (CGPoint)getCurrentPoint:(NSSet *)touches
{
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:touch.view];

    return point;
}
- (void)drawRect:(CGRect)rect
{
    //如果数组不为空就执行
    if (self.clickVSelectArr.count != 0) {
        //绘制路径
        UIBezierPath *path = [UIBezierPath bezierPath];
        //设置线宽
        path.lineWidth = LineWidth;
        //设置颜色
        self.isWrong ? (self.isTraOutOfPW ? [self.wrongColor set] : [[UIColor clearColor] set]) : (self.isTraOutOfPW ? [self.selectColor set] : [[UIColor clearColor] set]);
        //设置其实处样式
        path.lineCapStyle = kCGLineCapRound;
        //设置交点样式
        path.lineJoinStyle = kCGLineJoinRound;
        //设置起始点和线路
        for (NSInteger i=0; i < self.clickVSelectArr.count; i++) {
            WRGestureClickView * clickV = self.clickVSelectArr[i];
            CGPoint cen = clickV.center;
            if (i == 0 ) {
                [path moveToPoint:cen];
            }else{
                [path addLineToPoint:cen];
            }
            
        }
        //把最后一条线路添加进去
        [path addLineToPoint:self.currpoint];
        //绘制
        [path stroke];
    }
    
}
//设置错误密码以展示
- (void)showErrorClircles:(NSString *)string
{
    self.isWrong = YES;
    for (int index = 0; index < string.length; index ++) {
        NSRange range = NSMakeRange(index, 1);
        NSNumber * number = [NSNumber numberWithInt:[string substringWithRange:range].intValue - 1];
        [self.clickVArr[number.intValue] setSelected:YES];
        [self.clickVSelectArr addObject:self.clickVArr[number.intValue]];
        
    }
    for (WRGestureClickView * clickV in self.clickVArr) {
        if (clickV.selected) {
            [clickV setStateType:(self.isTraOutOfPW ? View_Click_Type_Wrong : View_Click_Type_Normal)];
        }
    }
    [self setNeedsDisplay];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(clearColorAndSelectClickV) userInfo:nil repeats:NO];
}

@end
